package com.bw.home.ui

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.CompoundButton
import com.bw.common.widget.NormalTitleBar
import com.bw.home.R
import com.bw.home.common.BitmapUtils
import com.bw.home.databinding.ActivityDetailBinding
import com.bw.home.model.entity.SimpleVideoEntity
import com.bw.home.widget.DanMuBottomDialog
import com.bw.home.widget.MyCacheStuffer
import com.bw.mvicore.common.ConstantValue
import com.bw.mvicore.ui.BaseActivity
import com.google.android.material.tabs.TabLayout
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import java.util.Random

class DetailActivity : BaseActivity() {
    private lateinit var binding: ActivityDetailBinding
    private var simpleVideoEntity: SimpleVideoEntity?=null
    private lateinit var descriptioniFragment: HomeDetailDescriptionFragment
    private lateinit var commentFragment: HomeDetailCommentFragment
    override fun releaseRes() {
    }

    override fun generateContentView(): View {
        binding = ActivityDetailBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        val bundle = intent.getParcelableExtra<Bundle>(ConstantValue.PARAMS)
        simpleVideoEntity = bundle?.getParcelable<SimpleVideoEntity>("entity")
        super.onCreate(savedInstanceState)
        /**
         * 标题栏设置title
         */
        binding.ntbHomeDetailTitlebar.setTitle(simpleVideoEntity?.title)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val bundle = intent?.getParcelableExtra<Bundle>(ConstantValue.PARAMS)
        simpleVideoEntity = bundle?.getParcelable<SimpleVideoEntity>("entity")
        /**
         * 标题栏设置title
         */
        binding.ntbHomeDetailTitlebar.setTitle(simpleVideoEntity?.title)
    }

    override fun initView() {
        super.initView()
        binding.gsyHomeDetail.titleTextView.visibility=View.GONE
        binding.gsyHomeDetail.backButton.visibility=View.GONE
        binding.gsyHomeDetail.fullscreenButton.setOnClickListener {
            binding.gsyHomeDetail.startWindowFullscreen(this@DetailActivity,false,true)
        }
        binding.gsyHomeDetail.isShowFullAnimation=true
        //关闭ijk内核log
        IjkPlayerManager.setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT)

        /**
         * 构建tab
         */
        binding.tabHomeDetailType.addTab(binding.tabHomeDetailType.newTab().setText("简介"))
        binding.tabHomeDetailType.addTab(binding.tabHomeDetailType.newTab().setText("评论"))

        descriptioniFragment= HomeDetailDescriptionFragment()
        val bundle:Bundle = Bundle()
        bundle.putParcelable("entity",simpleVideoEntity)
        descriptioniFragment.arguments=bundle
        commentFragment=HomeDetailCommentFragment()
        commentFragment.arguments=bundle
        /**
         * 默认加载简介Fragment
         */
        replaceFragment(R.id.fl_home_detail_content,descriptioniFragment)

        initDanMu()

        mHandler.postDelayed(object :Runnable{
            override fun run() {
                addDanmaku(false,"弹幕信息")
                mHandler.postDelayed(this,1000)
            }
        },1000)

    }

    /**
     * 主线程handler
     */
    private val mHandler:Handler= Handler()

    /**
     * 弹幕库上下文
     */
    private lateinit var dmContext:DanmakuContext
    /**
     * 背景的颜色
     */
    private val mContentColorBg = arrayOf("#0099ff", "#b2d15c", "#b9b9f1", "#f46c77")

    /**
     * 初始化弹幕
     */
    private fun initDanMu() {
        //设置最大显示行数
        val maxLInesPair: HashMap<Int, Int> = HashMap(16)
        maxLInesPair[BaseDanmaku.TYPE_SCROLL_RL] = 8
        //设置是否禁止重叠
        val overlappingEnablePair: HashMap<Int, Boolean> = HashMap(16)
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_RL] = true
        overlappingEnablePair[BaseDanmaku.TYPE_FIX_TOP] = true
        //创建弹幕上下文
        dmContext = DanmakuContext.create()
        //设置一些相关的配置
        dmContext.setDuplicateMergingEnabled(false) //是否重复合并
            .setScrollSpeedFactor(1.2f) //设置文字的比例
            .setScaleTextSize(1.2f) //图文混排的时候使用！这里可以不用
            .setCacheStuffer(MyCacheStuffer(this), mBackgroundCacheStuffer) //设置显示最大行数
            .setMaximumLines(maxLInesPair) //设置防，null代表可以重叠
            .preventOverlapping(overlappingEnablePair)


        if (binding.dvHomeDetail != null) {
            //设置解析器
            val defaultDanmakuParser = getDefaultDanmakuParser()
            //相应的回掉
            binding.dvHomeDetail.setCallback(object : DrawHandler.Callback {
                override fun updateTimer(timer: DanmakuTimer) {
                    //定时器更新的时候回掉
                }

                override fun drawingFinished() {
                    //弹幕绘制完成时回掉
                }

                override fun danmakuShown(danmaku: BaseDanmaku) {
                    //弹幕展示的时候回掉
                }

                override fun prepared() {
                    //弹幕准备好的时候回掉，这里启动弹幕
                    binding.dvHomeDetail.start()
                }
            })
            binding.dvHomeDetail.prepare(defaultDanmakuParser, dmContext)
            binding.dvHomeDetail.enableDanmakuDrawingCache(true)
        }
    }

    private val mBackgroundCacheStuffer: BaseCacheStuffer.Proxy =
        object : BaseCacheStuffer.Proxy() {
            override fun prepareDrawing(danmaku: BaseDanmaku, fromWorkerThread: Boolean) {
                // 根据你的条件检查是否需要需要更新弹幕
            }

            override fun releaseResource(danmaku: BaseDanmaku) {
                //清理相应的数据
                danmaku.tag = null
            }
        }

    private fun getDefaultDanmakuParser(): BaseDanmakuParser? {
        return object : BaseDanmakuParser() {
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }
    }

    /**
     * 装填弹幕并发送
     */
    private fun addDanmaku(islive: Boolean,content:String) {
        //创建一条弹幕
        val danmaku: BaseDanmaku =
            dmContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)

        if (danmaku == null || binding.dvHomeDetail == null) {
            return
        }

        //设置相应的数据
        var showBitmap: Bitmap = BitmapFactory.decodeResource(resources, R.mipmap.home_danmu)

        showBitmap = BitmapUtils.getShowPicture(showBitmap)
        val map: MutableMap<String, Any> = HashMap(16)
        map["content"] = content
        map["bitmap"] = showBitmap
        val random = Random()
        val randomNum: Int = random.nextInt(mContentColorBg.size)
        map["color"] = mContentColorBg.get(randomNum)
        //设置相应的tag
        danmaku.tag = map
        danmaku.textSize = 0f
        danmaku.padding = 10
        danmaku.text = ""
        // 一定会显示, 一般用于本机发送的弹幕
        danmaku.priority = 1
        danmaku.isLive = false
        danmaku.time = binding.dvHomeDetail.getCurrentTime()
        danmaku.textColor = Color.WHITE
        // 重要：如果有图文混排，最好不要设置描边(设textShadowColor=0)，否则会进行两次复杂的绘制导致运行效率降低
        danmaku.textShadowColor = 0
        //添加一条
        binding.dvHomeDetail.addDanmaku(danmaku)
//        showBitmap.recycle()
    }

    override fun initData() {
        binding.gsyHomeDetail.setUp(simpleVideoEntity?.videopath,true,"")
        //自动播放
        binding.gsyHomeDetail.startButton.performClick()

    }

    override fun initEvent() {
        /**
         * 标题栏返回按钮点击事件
         */
        binding.ntbHomeDetailTitlebar.setOnClickListener(object :NormalTitleBar.BackOnClickListener{
            override fun onClick() {
                closeThiz()
            }
        })

        /**
         * tab的切换事件
         */
        binding.tabHomeDetailType.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                when(tab?.text){
                    "简介" ->{
                        replaceFragment(R.id.fl_home_detail_content,descriptioniFragment)
                    }
                    "评论" ->{
                        replaceFragment(R.id.fl_home_detail_content,commentFragment)
                    }
                }
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })

        /**
         * 发送弹幕
         */
        binding.tvHomeDetailDanmu.setOnClickListener {
            val bottomDialog = DanMuBottomDialog(DetailActivity@this)
            bottomDialog.show()

            bottomDialog.setCallback {
                addDanmaku(false,it)
            }
        }

        binding.switchHomeDetailBulletscreen.setOnCheckedChangeListener(object :CompoundButton.OnCheckedChangeListener{
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (isChecked){
                    val defaultParser = getDefaultDanmakuParser()
                    binding.dvHomeDetail.prepare(defaultParser,dmContext)
                    binding.dvHomeDetail.resume()
                }
                else{
                    binding.dvHomeDetail.stop()
                }
            }

        })
    }

    override fun onResume() {
        super.onResume()
        binding.gsyHomeDetail.onVideoResume()
    }

    override fun onPause() {
        super.onPause()
        binding.gsyHomeDetail.onVideoPause()
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        if (handler!=null){
            handler.removeCallbacksAndMessages(null)
        }
    }
}